package com.example.jin.myapplication;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;

import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Created by jin on 2016/5/31.
 */

//AlertDialog建议在DialogFragment中使用

public class DatePickerFragment extends DialogFragment{
    public static int REQUEST_CODE=0x55;
    private static DatePickerFragment fragment=null;
    private static Date mDate;
    static synchronized DatePickerFragment Instance(Date date){
        if(fragment==null) {
            fragment = new DatePickerFragment();
        }
        mDate=date;
        return  fragment;
    }
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        //拥有FragmentManager的Activity会调用这个方法，然后返回一个DialogFragment
        View v= LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date,null);
        final DatePicker datePicker=(DatePicker)v.findViewById(R.id.datepicker);
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(mDate);

        datePicker.init(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH),null);
        return new AlertDialog.Builder(getActivity())
                .setTitle("Title")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int year=datePicker.getYear();
                        int month=datePicker.getMonth();
                        int day=datePicker.getDayOfMonth();
                        Date date=new GregorianCalendar(year,month,day).getTime();
                        sendResult(Activity.RESULT_OK,date);
                    }
                })
                .setView(v) //使用setView设置自定义视图
                .create();
    }

    private void sendResult(int resultcode,Date date){
        Fragment fragment=getTargetFragment();
        Intent intent=new Intent();
        intent.putExtra("date",date);
        if(fragment!=null)
            fragment.onActivityResult(REQUEST_CODE,resultcode,intent);
    }
}
